package es.indra.druida.desktop.configurator.beans.converters;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import es.indra.druida.desktop.configurator.beans.Icon;
import es.indra.druida.desktop.utils.DesktopWriter;

/**
 * The Class IconConverter.
 */
public class IconConverter {
	
	/**
	 * Bean array to json.
	 * 
	 * @param icons
	 *            the icons
	 * 
	 * @return the string
	 */
	public static String beanArrayToJson(Icon[] icons)	{
		StringBuffer jsonRet=new StringBuffer();
		jsonRet.append("[");
		for ( int i = 0 ; i < icons.length ; i++) {
			Icon icono=icons[i];
			if (i>0)
				jsonRet.append(",");
			jsonRet.append("{");
			jsonRet.append( "application:"+DesktopWriter.generaCadenaJavascript(icono.getApplication()) );
			jsonRet.append( ",file:"+DesktopWriter.generaCadenaJavascript(icono.getFile()) );
			jsonRet.append( ",x:"+icono.getX() );
			jsonRet.append( ",y:"+icono.getY() );
			jsonRet.append("}");			
		}
		jsonRet.append("]");
		return jsonRet.toString();
	}
	
	/**
	 * Json to bean array.
	 * 
	 * @param jsonIcons
	 *            the json icons
	 * 
	 * @return the icon[]
	 * 
	 * @throws JSONException
	 *             the JSON exception
	 */
	public static Icon[] jsonToBeanArray (String jsonIcons) throws JSONException	{
		JSONArray aIconos = new JSONArray(jsonIcons);
		Icon[] retIcons=new Icon[aIconos.length()];
		for (int r=0;r<aIconos.length(); r++){
			int x=0,y=0;
			String application=null,file=null;
			JSONObject oIcono= aIconos.getJSONObject(r);
			if (oIcono.has("x"))
				x=oIcono.getInt("x");
			if (oIcono.has("y"))
				y=oIcono.getInt("y");
			if(oIcono.has("application"))
				application=oIcono.getString("application");
			if(oIcono.has("file"))
				file=oIcono.getString("file");	
			retIcons[r]=new Icon(x,y,application,file);
		}
		return retIcons;
	}	
}

